package net.xinshi.controller;

import net.xinshi.domain.JsonResponseObject;
import net.xinshi.utils.ErrorCode;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author <a href="mailto:liukuo@xinshi.net">liukuo</a>
 * @version 1.0
 * @description
 * @since 2017/6/27.
 */
public class AbstractRestController {
    protected final static SimpleDateFormat TRANSACTION_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
    protected final static SimpleDateFormat SEND_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");

    protected final Logger logger = LogManager.getLogger(getClass());
    protected final boolean isLoggerDebugEnabled = logger.isDebugEnabled();


    /**
     * 将Spring对请求数据绑定过程中累积的Validation错误转化为JsonResponseObject。
     *
     * @param result
     * @return
     * @author wengyongyi
     */
    protected JsonResponseObject createValidErrorMsgAsRestResponse(BindingResult result) {
        List<FieldError> errors = result.getFieldErrors();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < errors.size(); i++) {
            if (i > 0) {
                sb.append(',');
            }
            sb.append(errors.get(i).getField())
                    .append(errors.get(i).getDefaultMessage());
        }
        JsonResponseObject jsonResponse = new JsonResponseObject();
        jsonResponse.setCode(ErrorCode.ERR_REST_INPUT_VALIDATION_REJECTED.getCode());
        jsonResponse.setMsg(sb.toString());
        jsonResponse.setTimestamp(new Date());
        return jsonResponse;
    }
}
